/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import DB.DBacess;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.basex.core.Context;
import org.basex.data.Result;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

/**
 *
 * @author jose
 */
public class configurador extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Context context = new Context();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            if (action.equals("addEncomenda")) {
                String tamanho = request.getParameter("tamanho");
                String massa = request.getParameter("massaSelect").split(",")[1];
                String[] ingrs = request.getParameterValues("ingredientes");
                String[] ingredientes = new String[ingrs.length];
                for (int i = 0; i < ingrs.length; i++) {
                    String[] split = ingrs[i].split(",");
                    ingredientes[i] = split[1];
                }
                double preco = Double.parseDouble(request.getParameter("preco"));
                String morada = request.getParameter("morada");
                try{
                    registarEncomenda(tamanho, massa, ingredientes, preco, morada);
                }catch(Exception e){
                    out.write("ERROR :" +e );
                }
                out.print("SUCESSS");
//
//                out.println("<html>");
//
//                out.println("<head>");
//
//                out.println("<title >teste</title>");
//
//                out.println("</head>");
//                out.println("<body>");
//                out.println("<h1> tamanho: " + tamanho + "</h1>");
//                out.println("massa:" + massa + "<br />");
//                out.println("<h1>ingredientes</h1>");
//                for (int i = 0; i < ingredientes.length; i++) {
//                    out.println(ingredientes[i]);
//                }
//                out.println("<h1>Morada :" + morada + "</h1>");
//                out.println("<h1>Preco:" + preco + "</h1>");
//
//                out.println("/body");

            } else if (action.equals("getXMLfile")) {
                String query = "doc('/home/jose/NetBeansProjects/websemantica-tp1/web/xml/BD/stock.xml')/stock/pizza";
                Result resultado = DBacess.executeQuery(query);
                response.setContentType("text/xml");
                response.setHeader("Cache-Control", "no-cache");
                response.getWriter().write(resultado.toString());
            } else {
                out.println("FAILED");
            }


        } catch (Exception e) {
            System.out.println(e);
            out.println("ERROR: " + e);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void registarEncomenda(String tamanho, String massa, String[] ingredientes, double preco, String morada) throws Exception {
        int id = getLastEncomendaID() + 1;
        DateFormat dataFormat = new SimpleDateFormat("yyyy/MM/dd");
        DateFormat tempoFormat = new SimpleDateFormat("HH:mm:ss");
        Date data = new Date();

        StringBuilder strbuilder = CreateBaseStringBuilder();
        strbuilder.append("<encomenda>\n");
        strbuilder.append("<id>").append(id).append("</id>\n");
        strbuilder.append("<data>").append(dataFormat.format(data)).append("</data>\n");
        strbuilder.append("<hora>").append(tempoFormat.format(data)).append("</hora>");
        strbuilder.append("<morada>").append(morada).append("</morada>\n");
        strbuilder.append("<preco>").append(preco).append("</preco>\n");
        strbuilder.append("<pizza>\n");
        strbuilder.append("<tamanho>").append(tamanho).append("</tamanho>");
        strbuilder.append("<massa>").append(massa).append("</massa>\n");
        strbuilder.append("<ingredientes>\n");
        for (int i = 0; i < ingredientes.length; i++) {
            strbuilder.append("<ingrediente>").append(ingredientes[i]).append("</ingrediente>");
        }
        strbuilder.append("</ingredientes>\n");
        strbuilder.append("</pizza>\n");
        strbuilder.append("</encomenda>");
        try {
            DBacess.addFile( strbuilder.toString(),"encomenda" + id);
            
        } catch (Exception e) {
            System.out.println(e);
        }
        updateNovaEncomenda(id,preco,morada,dataFormat.format(data),tempoFormat.format(data));
    }

    public int getLastEncomendaID() throws Exception {
        String query = "(doc('/home/jose/NetBeansProjects/websemantica-tp1/web/xml/BD/encomendas.xml')/encomendas/encomenda/id)[last()]";
        Result result = DBacess.executeQuery(query);
        int resultado = 0;
        Document xml = loadXMLFromString(result.toString());
        String x =xml.getDocumentElement().getFirstChild().getNodeValue().toString();
        resultado = Integer.parseInt(x);
        return resultado;
    }

    private static StringBuilder CreateBaseStringBuilder() {
        StringBuilder BaseDocument = new StringBuilder();
        BaseDocument.append("<?xml version=\"1.0\" encoding=\"utf-8\"?> \n");
        return (BaseDocument);
    }

    public static Document loadXMLFromString(String xml) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        return (Document) builder.parse(is);
    }

    private void updateNovaEncomenda(int id,double preco, String morada, String data, String hora) throws IOException {
        StringBuilder strbuilder = new StringBuilder();
        strbuilder.append("<encomenda>\n");
        strbuilder.append("<id>").append(id).append("</id>\n");
        strbuilder.append("<data>").append(data).append("</data>\n");
        strbuilder.append("<hora>").append(hora).append("</hora>");
        strbuilder.append("<morada>").append(morada).append("</morada>\n");
        strbuilder.append("<preco>").append(preco).append("</preco>\n");
        strbuilder.append("</encomenda>\n");
        String xmlfinal = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \n" + "<encomendas\n>"
                +DBacess.executeQuery("doc('/home/jose/NetBeansProjects/websemantica-tp1/web/xml/BD/encomendas.xml')/encomendas/encomenda")
                +strbuilder+"</encomendas\n>";
        DBacess.updateFile(xmlfinal,"encomendas.xml");
        
    }
}
